package net.xdclass.xdclass.service.impl;

import net.xdclass.xdclass.exception.XDException;
import net.xdclass.xdclass.mapper.EpisodeMapper;
import net.xdclass.xdclass.mapper.PlayRecordMapper;
import net.xdclass.xdclass.mapper.VideoMapper;
import net.xdclass.xdclass.mapper.VideoOrderMapper;
import net.xdclass.xdclass.model.pojo.Episode;
import net.xdclass.xdclass.model.pojo.PlayRecord;
import net.xdclass.xdclass.model.pojo.Video;
import net.xdclass.xdclass.model.pojo.VideoOrder;
import net.xdclass.xdclass.service.VideoOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class VideoOrderServiceImpl implements VideoOrderService {
    @Autowired
    VideoOrderMapper videoOrderMapper;
    @Autowired
    VideoMapper videoMapper;
    @Autowired
    EpisodeMapper episodeMapper;
    @Autowired
    PlayRecordMapper playRecordMapper;

    @Transactional
    @Override
    public int save(int userId, int videoId) {

        //判断是否已经购买
        VideoOrder videoOrder = videoOrderMapper.findByUserIdAndVideoIdAndState(userId, videoId, 1);

        if (videoOrder != null) {
            return 0;
        }

        Video video = videoMapper.findById(videoId);
        VideoOrder newVideoOrder = new VideoOrder();
        newVideoOrder.setCreateTime(new Date());
        newVideoOrder.setOutTradeNo(UUID.randomUUID().toString());
        newVideoOrder.setState(1);
        newVideoOrder.setTotalFee(video.getPrice());
        newVideoOrder.setUserId(userId);

        newVideoOrder.setVideoId(videoId);
        newVideoOrder.setVideoImg(video.getCoverImg());
        newVideoOrder.setVideoTitle(video.getTitle());
        int rows = videoOrderMapper.saveOrder(newVideoOrder);

        //生成播放记录
        if (rows==1){
           Episode episode = episodeMapper.findFirstEpisodeByVideoId(userId);
            if(episode == null){
                throw  new XDException(-1,"视频没有集信息，请运营人员检查");
            }
            PlayRecord playRecord = new PlayRecord();
            playRecord.setCreateTime(new Date());
            playRecord.setEpisodeId(episode.getId());
            playRecord.setCurrentNum(episode.getNum());
            playRecord.setUserId(userId);
            playRecord.setVideoId(videoId);
            playRecordMapper.saveRecord(playRecord);
        }
        return rows;
    }

    @Override
    public List<VideoOrder> listOrderByUserId(Integer userId) {
        List<VideoOrder> videoOrderList = videoOrderMapper.findById(userId);
        return videoOrderList;
    }
}
